package cn.qidisoft.edu.hzjt.controller.zyc;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.uuid.UUIDGenerator;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.KtglReviewGroup;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.TeacherThesis;
import cn.qidisoft.edu.hzjt.model.zyc.TeacherThesisAtt;
import cn.qidisoft.edu.hzjt.service.IKtglReviewGroupService;
import cn.qidisoft.edu.hzjt.service.zyc.ITeacherThesisAttService;
import cn.qidisoft.edu.hzjt.service.zyc.ITeacherThesisService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/***
 * 课题管理-提交论文
 */
@Controller
@RequestMapping(value = "teacherThesis")
public class TeacherThesisController {

    protected static final LoggerAdapter LOGGER =
            LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

    @Autowired
    ITeacherThesisService teacherThesisService;
    @Autowired
    ITeacherThesisAttService teacherThesisAttService;
    @Autowired
    IKtglReviewGroupService ktglReviewGroupService;

    private static String upload = null;

    static {
        upload = ApplicationContextConfigUtil.getString("file.path", null);
    }

    private static Map<String, List<TeacherThesisAtt>> picMap = new HashMap<>();

    @RequestMapping(value = "/index")
    public String index(ModelMap model, HttpServletRequest request) {
        request.setAttribute("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "zyc/teacherThesis/teacherThesisList";
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public ResponseResult list(
            ModelMap model, HttpServletRequest request,
            @RequestParam(value = "rows", required = false) String pageSize,
            @RequestParam(value = "page", required = false) String currentPage,
            TeacherThesis data) {
        try {
            data.setGid(UUIDGenerator.genReqID());
            UserEmployee userEmployee =
                    (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setEmpId(userEmployee.getEmid());
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            PaginationBean<TeacherThesis> paginationBean = teacherThesisService.queryPageList(data, page);
            ResponseResult result = new ResponseResult();
            result.setTotal(paginationBean.getTotalRecords());
            result.setRows(paginationBean.getPageList());
            return result;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 详情
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String info_teacherThesis(ModelMap model, HttpServletRequest request) {
        //获取详情
        String id = request.getParameter("id") == null ? "0" : request.getParameter("id");
        TeacherThesis entity = teacherThesisService.getBylwid(id);
        model.addAttribute("entity", entity);

        //获取附件信息
        TeacherThesisAtt att = new TeacherThesisAtt();
        att.setParentId(entity.getLwid());
        List<TeacherThesisAtt> attList = teacherThesisAttService.queryList(att);
        model.addAttribute("dataList", attList);

        KtglReviewGroup zjzGroup = ktglReviewGroupService.queryReviewGroupByPK(entity.getGroupid());
        if(zjzGroup == null){
            zjzGroup = new  KtglReviewGroup();
        }
        model.addAttribute("zjzGroup", zjzGroup);

        request.setAttribute("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "zyc/teacherThesis/info_teacherThesis";
    }

    @RequestMapping(value = "/addInInt", method = RequestMethod.GET)
    public String add(ModelMap model, HttpServletRequest request) {
        UserEmployee userEmployee =
                (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);

        TeacherThesis entity;
        //获取详情
        String id = request.getParameter("id");
        if (!StringUtils.isEmpty(id)) {
            entity = teacherThesisService.getBylwid(id);

            //获取附件信息
            TeacherThesisAtt att = new TeacherThesisAtt();
            att.setParentId(entity.getLwid());
            List<TeacherThesisAtt> attList = teacherThesisAttService.queryList(att);
            model.addAttribute("dataList", attList);
        }else{
            entity = new TeacherThesis();
            entity.setEmpName(userEmployee.getXm());
            entity.setCreateTime(new Date());
        }
        model.addAttribute("entity", entity);

        //专家组
        KtglReviewGroup record = new KtglReviewGroup();
        List<KtglReviewGroup> ktglReviewGroupList = ktglReviewGroupService.queryList(record);
        model.addAttribute("zjzList", ktglReviewGroupList);

        request.setAttribute("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "zyc/teacherThesis/teacherThesisAdd";
    }

    @SysLogger(description = "社团活动管理信息", moduleName = "社团活动管理", method = "新增保存")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(ModelMap model, HttpServletRequest request,
                       TeacherThesis data) {
        try {
            String type = request.getParameter("urlTp");//1#add保存（跳转info）|2#add保存并新增（跳转addInInt）|3#modify保存（跳转列表index）
            if (StringUtils.isEmpty(type)) {
                BaseController.setParameter("msg", "参数type丢失");
                return "redirect:index";
            }

            UserEmployee userEmployee =
                    (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
            //String action = request.getParameter("action")==null?"":request.getParameter("action");
            //data.setXkid(userEmployee.getEmid());

            data.setGid(UUIDGenerator.genReqID());
            if (data.getLwid() != null && data.getLwid() != 0) {
                TeacherThesis newData = new TeacherThesis();

                ConvertUtils.register(new DateConverter(null), java.util.Date.class);
                BeanUtils.copyProperties(newData, data);

                teacherThesisService.update(newData);

                BaseController.setParameter("msg", "修改成功");
            }else{
                data.setEmpId(userEmployee.getEmid());
                data.setAuditorId(userEmployee.getUid());
                data.setAuditorName(userEmployee.getXm());
                data.setEmpName(userEmployee.getXm());
                data.setCreateTime(new Date());
                teacherThesisService.insert(data);

                BaseController.setParameter("msg", "添加成功");

                TeacherThesis queryData = teacherThesisService.queryByPK(data);
                data.setLwid(queryData.getLwid());
            }


            String path = upload;
            List<TeacherThesisAtt> docFileResourceList = picMap
                    .get(String.valueOf(userEmployee.getUserid()));
            if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
                MultipartFile file = null;
                for (TeacherThesisAtt r : docFileResourceList) {
                    file = r.getMufile();
                    r.setParentId(data.getLwid());
                    String name = file.getOriginalFilename();// 获取上传文件名
                    InputStream in = r.getInputStream();// 获取文件对象
                    int pos = name.lastIndexOf(".");
                    String lastname = name.substring(pos, name.length());
                    // 文件保存的路径
                    String savePath = path + File.separator + r.getGid();
                    FileUtil.saveFile(savePath, in, r.getGid() + lastname);
                    r.setGid(r.getGid());// 附件id
                    r.setFileName(name);
                }
                teacherThesisAttService.batchInserts(docFileResourceList);
            }



            if ("1".equals(type)) {
                return "redirect:info?gid=" + data.getGid() + "&id=" + data.getLwid();//1#add保存（跳转info）
            } else if ("2".equals(type)) {
                return "redirect:addInInt";//2#add保存并新增（跳转addInInt）
            } else if ("3".equals(type)) {
                return "redirect:index";//3#modify保存（跳转列表index）
            } else {
                BaseController.setParameter("msg", "参数非法");
                return "redirect:index";
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            TeacherThesis data = new TeacherThesis();
            data.setIds(idList);
            teacherThesisService.delete(data);
            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }

    /**
     * 新增删除
     *
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload", method = RequestMethod.POST)
    public @ResponseBody void loadFile(@RequestParam("file") MultipartFile file,
                                       HttpServletRequest request, HttpServletResponse response) {
        List<TeacherThesisAtt> list = new ArrayList<>();
        UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
        List<TeacherThesisAtt> docFileResourceList = picMap
                .get(String.valueOf(userEmployee.getUserid()));
        // 本地env配置路径
        String path = upload;
        try {
            String gid = UUID.randomUUID().toString();
            String name = file.getOriginalFilename();// 获取上传文件名
            // 获取文件后缀名称
            String extend = FilenameUtils.getExtension(name);
            TeacherThesisAtt docFile = new TeacherThesisAtt();
            if (!file.isEmpty()) {
                // 文件的大小
                docFile.setFileSize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));
                docFile.setFileName(name);
                docFile.setGid(gid);
                docFile.setFilePath(gid + File.separator + gid + "." + extend);
                docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
                docFile.setMufile(file);
                docFile.setInputStream(file.getInputStream());
                docFile.setOrders(0);
                docFile.setSysfilepath(path + File.separator + gid + File.separator + gid + "." + extend);
                if (docFileResourceList != null && docFileResourceList.size() > 0) {
                    docFileResourceList.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
                } else {
                    list.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), list);
                }
                LOGGER.info("附件上传成功！");
            }
            PrintWriter writer = null;
            BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
            docFile2.setFilepath(docFile.getFilePath());
            // 文件名称
            docFile2.setFilename(docFile.getFileName());
            docFile2.setSysfilepath(path + File.separator + gid + File.separator + gid + "." + extend);
            writer = response.getWriter();
            String json = JSONObject.toJSONString(docFile2);
            writer.write(json);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增删除服务器的文件
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unused")
    @RequestMapping(value = "/deletefile", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> deleteFile(HttpServletRequest request) {

        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                    .getAttribute(Constant.LOGIN_CONSOLE_USER);
            // env配置路径
            String path = upload;
            String filepath = request.getParameter("filepath");
            LOGGER.info("文件的原始路径===" + filepath);
            // 文件名无后缀
            String fileNoSuffix = null;
            if (filepath.indexOf("prefix") == -1) {
                // 文件的文件名称
                fileNoSuffix = filepath.split(",")[0];
                String sec = filepath.split(",")[1];
                // 文件的后缀
                String suffix = sec.substring(sec.indexOf("."));
                // FileUtil.deleteFile(fullpath, filename);//删除文件目录下面的文件
                // FileUtils.forceDelete(new File(fullpath)); //删除文件目录
            } else {
                return dataMap;
            }
            List<TeacherThesisAtt> noticeNewsFilepathList = picMap
                    .get(String.valueOf(userEmployee.getUserid()));
            // 删除list里面前台删除的前台信息图片附件表
            if (noticeNewsFilepathList != null && !noticeNewsFilepathList.isEmpty()) {
                for (TeacherThesisAtt obj : noticeNewsFilepathList) {
                    if (obj.getFileName().equals(fileNoSuffix)) {
                        noticeNewsFilepathList.remove(obj);
                        break;
                    }
                }
            }
            // 先删除
            picMap.remove(userEmployee.getUserid());
            // 后添加
            picMap.put(String.valueOf(userEmployee.getUserid()), noticeNewsFilepathList);
            dataMap.put("success", "0000");
            return dataMap;
        } catch (Exception e) {
            dataMap.put("success", "-9999");
            return dataMap;
        }
    }


    /**
     *
     * @Title: source_upload_update
     * @Description: 删除附件
     * @param @param fileId
     * @param @param request
     * @param @param response
     * @param @return    参数
     * @return Map<String,Object>    返回类型
     * @throws
     */
    @RequestMapping(value = "/source_upload_update", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> source_upload_update(@RequestParam("fileId") String fileId,
                                                                  @RequestParam("filePath") String filePath,
                                                                  HttpServletRequest request,
                                                                  HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            //删除表记录
            TeacherThesisAtt attEntity = new TeacherThesisAtt();
            attEntity.setFileId(Integer.parseInt(fileId));

            TeacherThesisAtt newAttEntity = teacherThesisAttService.queryByFileId(attEntity);
            filePath = newAttEntity.getFilePath();
            teacherThesisAttService.delete(newAttEntity);

            //删除原始文件
            File file = new File(upload + File.separator + filePath);
            file.delete();

            //删除目录：实际上是删除最后一节也就是日期文件夹
            try {
                FileUtils.forceDelete(new File(upload + File.separator + filePath.substring(0, filePath.lastIndexOf("\\")))); //如果文件中所有的文件被删除了，还需要删除文件目录
            } catch (Exception e) {

            }

            dataMap.put("success", "0000");
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("success", "-9999");
        }
        return dataMap;
    }



    /*******************************************华丽的分隔符**********************************************************/
    /**
     *
     * @Title: exportPartyIncorrupt
     * @Description: 列表数据导出
     * @param @param request
     * @param @param response
     * @param @param data
     * @param @param model
     * @param @return
     * @param @throws Exception    参数
     * @return String    返回类型
     * @throws
     */
    @RequestMapping(value = "/export_teacherThesis")
    public @ResponseBody String export_teacherThesis(HttpServletRequest request,
                                                  HttpServletResponse response,
                                                     TeacherThesis data,
                                                  ModelMap model) throws Exception {
        try {
            List<TeacherThesis> queryList = teacherThesisService.queryList(data);

            String[][] title_name = { { "论文题目", "论文时间", "推荐结果", "获奖级别", "提交时间" } };
            String[] title_style = { "hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20",
                    "st_12_n_20"};
            String fileName = "提交论文";
            String[] remark = { "" };
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            if (queryList != null && !queryList.isEmpty()) {
                for (TeacherThesis res : queryList) {
                    Map<String, Object> map2 = new LinkedHashMap<String, Object>();
                    map2.put("subject", res.getSubject());
                    map2.put("lwsj", res.getLwsj());
                    map2.put("tjjg", res.getTjjg());
                    map2.put("hjjb", res.getHjjb());

                    map2.put("createTime", res.getCreateTime());
                    list.add(map2);
                }
            }
            HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark,
                    fileName, list);

            try {
                String filenameConvert = "提交论文";
                new String(fileName.getBytes("GB2312"), "ISO8859-1");
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + new String((filenameConvert + ".xls").getBytes(),
                                "iso-8859-1"));
                response.setDateHeader("Expires", 0);
                ServletOutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
            } catch (Exception e) {
                System.out.println("网络连接断开，可能用户取消了导出");
                model.addAttribute(Constant.EXPTION_MSG_KEY, e);
                return "error/error";
            }
        } catch (RPCException e) {
            LOGGER.error("获得提交论文 export_teacherThesis [{}] error,"
                            + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return null;
    }
}
